<?php
/*
PHP 加密解密 AES-256-CBC-Pkcs7Padding
*/
class EncryptUtil
{
    protected $cipher_algo;
    protected $key; // 32位
    protected $iv; // 16位

    /**
     * 加密
     */
    public function encrypt($data): string
    {
        if (is_array($data)) {
            $data = json_encode($data);
        }
        $cipher_algo = $this->getCipherAlgo();
        $key = $this->getkey();
        $iv = $this->getiv();
        return base64_encode(openssl_encrypt($data, $cipher_algo, $key, OPENSSL_RAW_DATA, $iv));
    }

    /**
     * 解密
     */
    public function decrypt($data): string
    {
        $cipher_algo = $this->getCipherAlgo();
        $key = $this->getkey();
        $iv = $this->getiv();
        return openssl_decrypt(base64_decode($data), $cipher_algo, $key, OPENSSL_RAW_DATA, $iv);
    }

    public function setCipherAlgo(string $cipher_algo)
    {
        $this->cipher_algo = $cipher_algo;
        return $this;
    }

    public function setkey(string $key)
    {
        $this->key = $key;
        return $this;
    }

    public function setIv(string $iv)
    {
        $this->iv = $iv;
        return $this;
    }

    public function getCipherAlgo(): string
    {
        return $this->cipher_algo;
    }

    public function getkey(): string
    {
        return $this->key;
    }

    public function getiv(): string
    {
        return $this->iv;
    }

}

$encryptUtil = new EncryptUtil;

$encryptUtil->setCipherAlgo("AES-256-CBC");
$encryptUtil->setkey("12345678901234567890123456789012");
$encryptUtil->setIv("1234567890123456");

$s = "hello world";
echo (sprintf("加密前字符串 [%s]\n", $s));

$encrypted = $encryptUtil->encrypt($s);
echo (sprintf("加密结果 [%s]\n", $encrypted));

$decrypted = $encryptUtil->decrypt("4MfPVKPCpqIlK9VOqf2N9w==");
echo (sprintf("解密结果 [%s]\n", $decrypted));
echo "==============================";
?>